<template>
	<search-row :gutter="12" style="width: 100%;margin-top: 15px;">
		<el-col :span="24">
			<!-- 搜索行 -->
			<search-row v-for="(rowItems, rowIndex) in visibleRows" :key="rowIndex">
				<template v-for="item in rowItems" :key="item.model">
					<component :is="item.component" v-model="searchForm[item.model]" v-bind="item.props"/>
				</template>
				<!-- 搜索按钮放在最后一列，补齐空列 -->
				<search-button
					v-if="rowIndex === visibleRows.length - 1"
					:span="buttonSpan(rowItems.length)"
					:md="buttonSpan(rowItems.length)"
					:expand="expand"
					:show-expand="showExpandButton"
					@search="searchClick"
					@reset="resetClick"
					@expand="$emit('expand', !expand)"
				/>
			</search-row>
		</el-col>
	</search-row>
</template>

<script setup lang="ts">
import {computed} from 'vue';
import SearchRow from '@/components/lcSearch/row.vue';
import SearchButton from '@/components/lcSearch/button.vue';
import {FcTableInstance} from "@/components/fcTable/model.ts";

const props = defineProps({
	searchItems: {type: Array, required: true},
	searchForm: {type: Object, required: true},
	expand: {type: Boolean, default: false},
	fcTableRef: {type: Object as () => FcTableInstance | null, default: null},
});

const emit = defineEmits(['expand']);

// 第一行最多显示 3 个搜索框
const maxFirstRow = 3;

// 展开按钮是否显示
const showExpandButton = computed(() => props.searchItems.length > maxFirstRow);

// 所有行
const allSearchRows = computed(() => {
	const items = [...props.searchItems];
	const rows: any[] = [];
	let temp: any[] = [];
	items.forEach(item => {
		temp.push(item);
		if (temp.length === 4) {
			rows.push([...temp]);
			temp = [];
		}
	});
	if (temp.length > 0) rows.push([...temp]);
	return rows;
});

// 当前显示的行
const visibleRows = computed(() =>
	!props.expand ? [props.searchItems.slice(0, maxFirstRow)] : allSearchRows.value
);

// 计算按钮占位 span
const buttonSpan = (rowItemsLength: number) => {
	const remainder = rowItemsLength % 4;
	const emptyCols = remainder === 0 ? 4 : 4 - remainder;
	return emptyCols * 6 || 6;
};

const searchClick = () => {

	// 判断 searchForm 所有字段是否都为空
	const allEmpty = Object.values(props.searchForm).every(
		(val) => val === null || val === undefined || val === ''
	);
	console.log(allEmpty);
	if (allEmpty) return;
	if (!props.fcTableRef) return;
	props.fcTableRef!.searchParam = {...props.searchForm};
	props.fcTableRef!.getTableList();
};

const resetClick = () => {
	for (const k in props.searchForm) {
		props.searchForm[k as keyof typeof props.searchForm] = null
	}
	props.fcTableRef!.reset()
};
</script>
